package services

import (
	"context"
	"errors"
	"fmt"
	"github.com/garyburd/redigo/redis"
	"math/rand"
	"time"
)
import "codeserver/proto"

type ServicesA struct {}

func  GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func UseRedis () (redis.Conn , error) {
	con , err := redis.Dial("tcp" , ":6379")
	if err != nil {
		return con , err
	}
	return con , nil
}
func (s ServicesA) GetCode(c context.Context, req *codeserver.GetCodeReuqest) (*codeserver.RCodeResponse, error) {
	con , err := UseRedis()
	if err != nil {
		return nil , errors.New("the redis databases is not work")
	}
	randstr :=  GetRandomString(10)
	_ , err = con.Do("hset" , req.UserId , "code" , randstr)
	con.Do("set" , randstr , req.UserId , "EX" , 120)
	con.Do("EXPIRE" , req.UserId , 20)
	if err != nil {
		return nil , errors.New("data is not insert")
	}
	return &codeserver.RCodeResponse{Code: randstr} , nil
}

func (s ServicesA) Isvalid(c context.Context, req *codeserver.ValidRequest) (*codeserver.ValidResponse, error) {
	con , err := UseRedis()
	if err != nil {
		return nil , errors.New("the databses is not work")
	}
	r , err := con.Do("get" , req.Code)
	if err != nil {
		return nil , err
	}
	if r == nil {
		fmt.Println("now")
		return &codeserver.ValidResponse{IsValid: false} , nil
	} else {
		return &codeserver.ValidResponse{IsValid: true} , nil
	}
}
